/*
Copyright 2009 Jeff Carnes

This file is part of Fluant.

Fluant is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

Fluant is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.amiasleep.fluant.jsfl;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;

public class JSFLRunnerTask extends Task {
	
	private File jsflFile;
	private FileSet jsflFileSet;
	private int timeout = JSFLRunner.DEFAULT_TIMEOUT;
	private boolean failOnError = true;
	private boolean failOnWarning = false;
	private boolean closeFlash = false;
	
	
	
	public void execute() throws BuildException
	{
		try
		{
			ArrayList<File> files = new ArrayList<File>();
			
			if(jsflFileSet != null)
			{
				DirectoryScanner ds = jsflFileSet.getDirectoryScanner( getProject() );
				String[] fileNames = ds.getIncludedFiles();
				
				File fileToAdd;
				for(int i=0; i < fileNames.length; i++)
				{
					fileToAdd = new File(ds.getBasedir() + File.separator + fileNames[i]);
					files.add(fileToAdd);
				}
			}
			else if(jsflFile != null)
			{
				files.add(jsflFile);
			}
			else
			{
				throw new BuildException("No JSFL files were specified");
			}
			
			File currentJSFL;
			for(int i=0; i < files.size(); i++)
			{
				currentJSFL = files.get(i);
				JSFLRunner runner = new JSFLRunner(currentJSFL, timeout);
				// Only allow Flash to be closed if it's the last file being processed
				if(i == files.size() - 1)
				{
					runner.closeFlashWhenFinished = closeFlash;
				}
				runner.run();
			}
		}
		catch(Exception ex)
		{
			if(failOnError)
			{
				throw new BuildException(ex);
			}
			else
			{
				log(ex.toString());
			}
		}
		
	}
	
	
	
	public void setFile(File file)
	{
		jsflFile = file;
	}
	
	
	
	public void addConfigured(FileSet set)
	{
		jsflFileSet = set;
	}
	
	
	
	public void setTimeout(int duration)
	{
		timeout = duration;
	}
	
	
	
	public void setFailOnError(boolean doFail)
	{
		failOnError = doFail;
	}
	
	
	
	public void setFailOnWarning(boolean doFail)
	{
		failOnWarning = doFail;
	}
	
	
	
	public void setCloseFlash(boolean close)
	{
		closeFlash = close;
	}

}
